package com.read.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.read.mapper.BookMapper;
import com.read.service.BookService;
import com.read.config.RedisKey;
import com.read.entity.Book;
import com.read.resp.BaseResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName BookServiceImpl
 * @Description TODO
 * @Author young
 * @Date 2022-11-05 12:47
 * @Version 1.0
 **/
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    @Autowired
    BookMapper bookMapper;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public BaseResp getBookByBookId(String bookId) {

        Boolean aBoolean = redisTemplate.opsForHash().hasKey(RedisKey.BOOK_INFO, bookId);
        if (!aBoolean){
            Book book = bookMapper.getBookByBookId(bookId);
            if (book!=null){
                redisTemplate.boundHashOps(RedisKey.BOOK_INFO).put(bookId,book);
            }else{
                redisTemplate.opsForValue().set(RedisKey.BOOK_INFO,null,10, TimeUnit.SECONDS);
            }
        }
        Object o = redisTemplate.boundHashOps(RedisKey.BOOK_INFO).get(bookId);
        return new BaseResp().Success("图书基本信息查询成功!",o,null);
    }

    @Override
    public BaseResp getBookDetailsByBoodId(String bookId) {
        Boolean aBoolean = redisTemplate.opsForHash().hasKey(RedisKey.BOOK_DETAILS, bookId);
        if (!aBoolean){
            Book book = bookMapper.getBookDetailsByBoodId(bookId);
            if (book!=null){
                redisTemplate.boundHashOps(RedisKey.BOOK_DETAILS).put(bookId,book);
            }else{
                redisTemplate.opsForValue().set(RedisKey.BOOK_DETAILS,null,10,TimeUnit.SECONDS);
            }

        }
        Object o = redisTemplate.boundHashOps(RedisKey.BOOK_DETAILS).get(bookId);
        return new BaseResp().Success("图书详情查询成功!",o,null);
    }
}
